package gl.android.jxzs.socket;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

/**
 * @author Administrator
 * 
 */
public class MessageReceiver {
	final String CHARSET = "UTF-8";
	private DataInputStream dis;
	ReceiveThread receiveThread;
	private boolean runflag;
	ArrayList<MessageHandler> mMessageHandlerList = new ArrayList<MessageHandler>();

	public MessageReceiver(DataInputStream dis) {
		this.dis = dis;
		receiveThread = new ReceiveThread();
		runflag = true;
		receiveThread.start();
	}

	public void addMessageHandler(MessageHandler mPacketHandler) {
		mMessageHandlerList.add(mPacketHandler);
	}

	public void close() {
		runflag = false;
		mMessageHandlerList.clear();
	}

	class ReceiveThread extends Thread {
		@Override
		public void run() {

			System.out.println("ReceiveThread is runing");
			while (runflag) {
				try {
					int contentSize = 100 * 1024;
					System.out.println("IO<read..");
					byte[] buffer = new byte[contentSize];
					int readBytes = dis.read(buffer);
					handle(buffer, readBytes);
				} catch (IOException e) {
					runflag = false;
					e.printStackTrace();
				}
			}

		}
	}

	public void handle(byte[] packet, int length)
			throws UnsupportedEncodingException {
		for (MessageHandler mMessageHandler : mMessageHandlerList) {
			mMessageHandler.handle(new String(packet, 0, length, "GBK"));
		}

	}

}
